<template>
  <div class="pay-order">
    <BaseHeader></BaseHeader>
    <!-- LOGO 步骤条 -->
    <div class="width_1200 logo">
      <div>
        <router-link to="/"><img :src="$store.state.logoImg" /></router-link>
        <div style="margin-top: 15px">结算页</div>
      </div>
      <div class="cart-steps">
        <span :class="stepIndex == 1 ? 'active' : ''">1.我的预订</span>
        <Icon :class="stepIndex == 1 ? 'active-arrow' : ''" custom="icomoon icon-next"></Icon>
        <span :class="stepIndex == 1 ? 'active' : ''">2.订单信息</span>
        <Icon :class="stepIndex == 1 ? 'active-arrow' : ''" custom="icomoon icon-next"></Icon>
        <span :class="stepIndex == 2 ? 'active' : ''">3.成功提交</span>
      </div>
    </div>
    <Divider />
    <div class="content width_1200">
      <!-- 收货地址 -->
      <div class="address" v-if="selectedDeliverMethod === 'LOGISTICS' && goodsType === 'PHYSICAL_GOODS'">
        <div class="card-head">
          <span>收货人信息</span>
          <span @click="goAddressManage">管理收货人地址</span>
        </div>
        <div class="address-manage">
          <div
            class="address-item"
            v-show="moreAddr ? true : index < 3"
            :class="selectedAddress.id === item.id ? 'border-red' : ''"
            @mouseenter="showEditBtn = index"
            @mouseleave="showEditBtn = ''"
            @click="selectAddress(item)"
            v-for="(item, index) in addressList"
            :key="index"
          >
            <div>
              <span>{{ item.name }}</span>
              <Tag class="ml_10" v-if="item.isDefault" color="red">默认</Tag>
              <Tag class="ml_10" v-if="item.alias" color="warning">{{ item.alias }} </Tag>
            </div>
            <div>{{ item.mobile }}</div>
            <div>{{ item.consigneeAddressPath | unitAddress }} {{ item.detail }}</div>
            <div class="edit-btn" v-show="showEditBtn === index">
              <span @click.stop="editAddress(item.id)">修改</span>
              <span class="ml_10" v-if="!item.isDefault" @click.stop="delAddress(item)">删除</span>
            </div>
            <div class="corner-icon" v-show="selectedAddress.id === item.id">
              <div></div>
              <Icon type="md-checkmark" />
            </div>
          </div>
          <div class="add-address" @click="editAddress('')">
            <Icon type="ios-add-circle-outline" />
            <div>添加新地址</div>
          </div>
        </div>
        <div class="more-addr" @click="moreAddr = !moreAddr" v-if="addressList.length > 3">
          {{ moreAddr ? '收起地址' : '更多地址' }}
          <Icon v-show="!moreAddr" type="md-arrow-dropdown" />
          <Icon v-show="moreAddr" type="md-arrow-dropup" />
        </div>
      </div>

      <!-- 自提点信息 -->
      <div class="address" v-if="selectedDeliverMethod === 'SELF_PICK_UP'">
        <div class="card-head">
          <span>自提点信息</span>
        </div>
        <div class="address-manage">
          <div
            class="address-item"
            v-show="storeMoreAddr ? true : index < 3"
            :class="selectedAddress.id === item.id ? 'border-red' : ''"
            @mouseenter="showEditBtn = index"
            @mouseleave="showEditBtn = ''"
            @click="selectStoreAddress(item)"
            v-for="(item, index) in storeAddressList"
            :key="index"
          >
            <div>
              <span>{{ item.addressName }}</span>
            </div>
            <div>{{ item.mobile }}</div>
            <div>{{ item.address | unitAddress }} {{ item.detail }}</div>
            <div class="corner-icon" v-show="selectedStoreAddress.id === item.id">
              <div></div>
              <Icon type="md-checkmark" />
            </div>
          </div>
        </div>
        <div class="more-addr" @click="storeMoreAddr = !storeMoreAddr" v-if="addressList.length > 3">
          {{ storeMoreAddr ? '收起地址' : '更多地址' }}
          <Icon v-show="!storeMoreAddr" type="md-arrow-dropdown" />
          <Icon v-show="storeMoreAddr" type="md-arrow-dropup" />
        </div>
      </div>

      <div></div>

      <!-- 配送方式 -->
      <div class="goods-content" v-if="goodsType === 'PHYSICAL_GOODS'">
        <div class="card-head mt_20 mb_20">
          <span>配送方式</span>
        </div>
        <div class="delivery-method">
          <div
            class="method-item"
            v-show="moreAddr ? true : index < 3"
            :class="selectedDeliverMethod === item.value ? 'border-red' : ''"
            @mouseenter="showEditBtn = item.value"
            @mouseleave="showEditBtn = ''"
            @click="selectDeliverMethod(item)"
            v-for="(item, index) in shippingMethod"
            :key="index"
          >
            <div>{{ item.label }}</div>
            <div class="corner-icon" v-show="selectedDeliverMethod === item.value">
              <div></div>
              <Icon type="md-checkmark" />
            </div>
          </div>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="goods-content">
        <div class="card-head mt_20 mb_20">
          <span>产品信息</span> {{ goodsId }} 
          <!--span @click="$router.push('/cart')">返回预订</span-->
        </div>

        <div class="goods-msg" v-for="(shop, shopIndex) in goodsList" :key="shopIndex">
          <div v-if="shop.checked">
            <!--div class="shop-name">
            <span>
              <span class="hover-color" @click="goShopPage(shop.storeId)">{{
                  shop.storeName
              }}</span>&nbsp;&nbsp;
            </span>
          </div @click="goGoodsDetail(goods.goodsSku.id, goods.goodsSku.goodsId)"
          -->
            <div class="goods-list">
              <div class="goods-item" v-for="(goods, goodsIndex) in shop.checkedSkuList" :key="goodsIndex">
                <div class="goods-info" style="display: block">
                  <span class="hover-color">
                    <img :src="pictureUrl(goods.goodsSku.thumbnail)" alt="" style="float: left" />
                    <div style="float: left; margin-left: 10px">
                      <div style="vertical-align: top; font-size: 18px; font-weight: 800; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 1000px">
                        {{ goods.goodsSku.goodsName }}
                      </div>
                      <!-- 优惠券展示 -->
                      <div class="n4" style="width: 350px; margin-top: 9px">
                        <p class="Ellipsis">
                          <span class="item-price-title">出团日期</span><i>：</i>
                          <span class="item-coupon">{{ goods.tourDate }}（{{ goods.weekName }}）</span>
                        </p>
                        <p class="Ellipsis">
                          <span class="item-price-title">优惠</span><i>：</i>
                          <span class="item-coupon">
                            <span>同行优惠</span> <span>{{ goods.goodsSku.priceVip }}元/人</span>
                          </span>
                          <span class="item-coupon">
                            <span>会员优惠</span> <span>{{ goods.goodsSku.priceRoom }}元/人</span>
                          </span>
                        </p>
                      </div>
                    </div>
                  </span>
                  <!--label v-if="goodsType === 'TOUR_GOODS'">
                  <span style="margin-right: 20px;">{{ goods.num || 0 }}成人 x {{ goods.goodsSku.price | unitPrice("￥") }}</span>
                  <span v-if="goods.childNum > 0">{{ goods.childNum || 0 }}儿童 x {{ goods.goodsSku.priceChild | unitPrice("￥") }}</span>
                </label>
                <label v-else>
                  <span class="goods-price">{{ goods.purchasePrice | unitPrice("￥") }}</span>
                  <span>x{{ goods.num }}</span>
                  <span>{{ goods.goodsSku.quantity > 0 ? "有货" : "无货" }}</span>
                </label-->
                </div>

                <ul class="supplement">
                  <li class="supplement_tit">
                    <span>名称</span>
                    <span>单价</span>
                    <span>单位</span>
                    <span>数量</span>
                    <span>小计</span>
                  </li>
                  <li class="supplement_text">
                    <span>成人</span>
                    <span>{{ goods.goodsSku.price | unitPrice('￥') }}</span>
                    <span>元/人</span>
                    <span>
                      <!--em id="num_reduce" @click="handleReduce('adult')">-</em>
                    <strong id="num">{{ goods.num || 0 }}</strong>
                    <em id="num_plus" @click="handleAdd('adult')">+</em-->
                      <InputNumber
                        :min="1"
                        size="small"
                        controls-outside
                        autocomplete="off"
                        style="width: 100px; text-align: right"
                        v-model="goods.num"
                        @on-change="changeNum(goods.num, goods.childNum, goods.goodsSku.id)"
                      ></InputNumber>
                    </span>
                    <span class="col48" id="singleTotalPrice">{{ ((goods.num || 0) * goods.goodsSku.price) | unitPrice('￥') }}</span>
                  </li>
                  <li class="supplement_text">
                    <span>儿童</span>
                    <span>{{ goods.goodsSku.priceChild | unitPrice('￥') }}</span>
                    <span>元/人</span>
                    <span>
                      <!--em id="num_reduce" @click="handleReduce('child')">-</em>
                    <Input type="text" min="0" size="small" id="childNum" onblur="CheckStock()" :value="goods.childNum || 0" style="width: 50px; text-align: center;"/>
                    <em id="num_plus" @click="handleAdd('child')">+</em-->
                      <InputNumber
                        :min="0"
                        size="small"
                        controls-outside
                        autocomplete="off"
                        style="width: 100px; text-align: right"
                        v-model="goods.childNum"
                        @on-change="changeNum(goods.num, goods.childNum, goods.goodsSku.id)"
                      ></InputNumber>
                    </span>
                    <span class="col48" id="singleTotalPrice">{{ ((goods.childNum || 0) * goods.goodsSku.priceChild) | unitPrice('￥') }}</span>
                  </li>
                  <li class="supplement_text">
                    <span>增项</span>
                    <span style="width: 200px; padding-left: 60px">
                      <Input type="text" v-model.lazy="goods.addPrice" placeholder="金额" style="width: 100px" @on-blur="changeItemPriceBlur(goods.addPrice, goods.subPrice, goods.goodsSku.id)" />
                    </span>
                    <span style="width: 500px; padding-left: 110px">
                      <Input type="text" v-model="goods.addMark" placeholder="说明" style="width: 500px" @on-blur="changeItemMarkBlur(goods.addMark, goods.subMark, goods.goodsSku.id)" />
                    </span>
                  </li>
                  <li class="supplement_text">
                    <span>减项</span>
                    <span style="width: 200px; padding-left: 60px">
                      <Input type="text" v-model.lazy="goods.subPrice" placeholder="金额" style="width: 100px" @on-blur="changeItemPriceBlur(goods.addPrice, goods.subPrice, goods.goodsSku.id)" />
                    </span>
                    <span style="width: 500px; padding-left: 110px">
                      <Input type="text" v-model="goods.subMark" placeholder="说明" style="width: 500px" @on-blur="changeItemMarkBlur(goods.addMark, goods.subMark, goods.goodsSku.id)" />
                    </span>
                  </li>
                </ul>
              </div>
            </div>

            <div class="goods-bottom">
              <div class="order-mark">
                <Input type="textarea" maxlength="100" v-model="shop.remark" show-word-limit placeholder="订单备注" :rows="6" />
                <span style="font-size: 12px; color: #999">
                  <!-- 提示：请勿填写有关支付、收货、发票方面的信息 -->
                </span>
              </div>

              <!-- 订单价格 -->
              <div class="order-price">
                <div>
                  <span>团款金额：</span><span>{{ priceDetailDTO.goodsPrice | unitPrice('￥') }}</span>
                </div>
                <div>
                  <span>增项金额：</span><span>{{ priceDetailDTO.addPrice | unitPrice('￥') }}</span>
                </div>
                <div v-if="priceDetailDTO.freightPrice > 0">
                  <span>运费：</span><span>{{ priceDetailDTO.freightPrice | unitPrice('￥') }}</span>
                </div>
                <div v-if="priceDetailDTO.discountPrice > 0">
                  <span>优惠金额：</span><span>-{{ priceDetailDTO.discountPrice | unitPrice('￥') }}</span>
                </div>
                <div v-if="priceDetailDTO.couponPrice > 0">
                  <span>优惠抵券：</span><span>-{{ priceDetailDTO.couponPrice | unitPrice('￥') }}</span>
                </div>
                <div>
                  <span>减项金额：</span>
                  <span v-if="priceDetailDTO.subPrice > 0">-{{ priceDetailDTO.subPrice | unitPrice('￥') }}</span>
                  <span v-else>{{ priceDetailDTO.subPrice | unitPrice('￥') }}</span>
                </div>
                <div v-if="$route.query.way === 'POINTS'">
                  <span>应付积分：</span><span class="actrual-price">{{ priceDetailDTO.payPoint }}</span>
                </div>
                <div v-else>
                  <span>应付金额：</span><span class="actrual-price">{{ priceDetailDTO.flowPrice | unitPrice('￥') }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 优惠券 -->
      <div class="invoice" v-if="couponList.length > 0">
        <div class="card-head mt_20 mb_20">
          <span class="relative">优惠券</span>
        </div>
        <div v-if="couponList.length === 0">无可用优惠券</div>
        <ul v-else class="coupon-list">
          <li v-for="(item, index) in couponList" class="coupon-item" :key="index">
            <div class="c-left">
              <div>
                <span v-if="item.couponType === 'PRICE'" class="fontsize_12 global_color"
                  >￥<span class="price">{{ tem.price | unitPrice }}</span></span
                >
                <span v-if="item.couponType === 'DISCOUNT'" class="fontsize_12 global_color"
                  ><span class="price">{{ item.discount }}</span
                  >折</span
                >
                <span class="describe">满{{ item.consumeThreshold }}元可用</span>
              </div>
              <p>使用范围：{{ useScope(item.scopeType) }}</p>
              <p>有效期：{{ item.endTime }}</p>
            </div>
            <img class="used" v-if="usedCouponId.includes(item.id)" src="../../assets/images/geted.png" alt="" />
            <b></b>
            <a class="c-right" @click="useCoupon(item.id, true)">立即使用</a>
            <a class="c-right" v-if="usedCouponId.includes(item.id)" @click="useCoupon(item.id, false)">放弃优惠</a>
            <i class="circle-top"></i>
            <i class="circle-bottom"></i>
          </li>
        </ul>
      </div>

      <!-- 游客信息 -->
      <div class="invoice" v-if="goodsType === 'TOUR_GOODS'">
        <div class="card-head mt_20">
          <span class="relative">游客信息</span>
        </div>
        <div class="inovice-content">
          <vxe-table
            border
            size="small"
            resizable
            keep-source
            show-overflow
            ref="xTable"
            :data="visitors"
            :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, icon: 'vxe-icon-edit' }"
            :edit-rules="validRules"
            @edit-closed="editClosedEvent"
          >
            <vxe-column type="seq" width="50" align="center"></vxe-column>
            <vxe-column field="name" title="姓名" width="188" :edit-render="{ autofocus: '.vxe-input--inner', placeholder: '请点击输入姓名' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.name" class="input-name" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="type" title="证件类型" width="180" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #default="{ row }">
                <span>{{ formatCertType(row.type) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.type" transfer>
                  <vxe-option v-for="item in certList" :key="item.value" :value="item.value" :label="item.label"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="number" title="证件号" width="283" align="center" :edit-render="{ autofocus: '.vxe-input--inner', placeholder: '请点击输入证件号' }">
              <template #edit="{ row }">
                <Input v-model="row.number" type="text"></Input>
              </template>
            </vxe-column>
            <vxe-column field="sex" title="性别" width="133" align="center" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ formatSex(row.sex) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.sex" transfer>
                  <vxe-option v-for="item in sexList" :key="item.value" :value="item.value" :label="item.label"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="age" title="年龄" width="133" align="center" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.age" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="tel" title="联系电话" width="183" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.tel" type="text" transfer></vxe-input>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>

      <!-- 发票信息 开企业抬头发票须填写纳税人识别号，以免影响报销 -->
      <div class="invoice" v-if="goodsType !== 'TOUR_GOODS'">
        <div class="card-head mt_20">
          <span class="relative">发票信息<span class="inv-tips"><Icon type="ios-alert-outline" /></span></span>
        </div>
        <div class="inovice-content">
          <span>{{ invoiceData.receiptTitle }}</span>
          <span>{{ invoiceData.receiptContent }}</span>
          <span @click="editInvoice">编辑</span>
        </div>
      </div>
    </div>

    <!-- 底部支付栏 -->
    <div class="order-footer width_1200">
      <div class="order-footer-in">
        <div class="pay ml_20" @click="pay">提交订单</div>
        <div class="pay-address flex flex-wrap justify-center gap-8 px-2 mt-1" v-if="advisers.list.length">
          <div v-for="(advisor, index) in advisers.list" :key="index" :id="advisor.id" class="relative" @click="shippingAdviser(index, advisor.id)">
            <div class="advisor-card flex flex-col items-center adviser" :class="{ 'active': advisers.index == index }">
              <div class="relative group">
                <img :src="$config.staticDomainURL + '/' + advisor.headimgurl"
                  class="w-6 h-6 rounded-full object-cover cursor-pointer shadow-md hover:shadow-lg transition-shadow duration-300 m-auto"
                />
                <h3 class="mt-2 text-gray-600 font-medium items-center text-center">
                  {{ advisor.skrName }}
                </h3>
              </div>
            </div>
          </div>
        </div>
        <div class="pay-address" v-if="addressList.length && selectedDeliverMethod === 'LOGISTICS'">
          配送至：{{ selectedAddress.consigneeAddressPath | unitAddress }} {{ selectedAddress.detail }}&nbsp;&nbsp; 收货人：{{ selectedAddress.name }}&nbsp;&nbsp;{{ selectedAddress.mobile }}
        </div>
        <div class="pay-address" v-if="addressList.length && selectedDeliverMethod === 'SELF_PICK_UP'">
          自提地点：{{ selectedStoreAddress.address }} &nbsp;&nbsp; 联系方式：{{ selectedStoreAddress.mobile }}
        </div>
      </div>
    </div>

    <!--BaseFooter></BaseFooter-->

    <!-- 添加发票模态框 -->
    <invoice-modal ref="invModal" :invoiceData="invoiceData" @change="getInvMsg" />
    <!-- 选择地址模态框 -->
    <address-manage ref="address" :id="addrId" @change="addrChange"></address-manage>
  </div>
</template>

<script>
import invoiceModal from '@/components/invoiceModal';
import addressManage from '@/components/addressManage';
import { staticUrl } from '@/plugins/request';
import { memberAddress, delMemberAddress } from '@/api/address';
import { cartGoodsPay, createTrade, selectAddr, selectCoupon, setShipMethod, setStoreAddressId, shippingMethodList, couponNum, setCartGoodsNum, setCartItemPrice, setCartItemMark, setShippingAdviser } from '@/api/cart';
import { getStoreAddress } from '@/api/shopentry.js';
import { canUseCouponList } from '@/api/member.js';
import { adviserList } from '@/api/adviser.js';
import { visitorCache, visitorList } from '@/api/visitor.js';
import { hashFnv32a } from '@/plugins/Foundation.js';
import { getAgeByIdCard, getSexByIdCard, IdentityCode_isCardNo } from '@/plugins/IdCard.js';
import { Input } from 'view-design';

export default {
  name: 'Pay',
  components: {
    invoiceModal,
    addressManage,
  },
  data() {
    const numberValid = ({ cellValue, row }) => {
      // 模拟服务端校验
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (row.type == '1' && !IdentityCode_isCardNo(cellValue)) {
            reject(new Error('身份证号码格式不正确！'));
          } else {
            resolve();
          }
        }, 100);
      });
    };
    return {
      selectedStoreAddress: 'm',
      selectMethod: '',
      stepIndex: 1, // 顶部步骤条状态
      invoiceAvailable: false, // 发票编辑按钮
      showEditBtn: '', // 鼠标移入显示编辑按钮
      orderMark: '', // 订单备注
      goodsType: '', // 商品类型
      storeMoreAddr: false,
      invoiceData: {
        // 发票数据
        receiptTitle: '个人',
        receiptContent: '不开发票',
      },
      searchForm: {
        pageNumber: 1,
        pageSize: 100,
      },
      shippingMethod: [],
      storeAddressList: [],
      shippingWay: [
        {
          value: 'LOGISTICS',
          label: '物流',
        },
        {
          value: 'SELF_PICK_UP',
          label: '自提',
        },
      ],
      selectedDeliverMethod: 'LOGISTICS',
      addressList: [], // 地址列表
      selectedAddress: {}, // 所选地址
      goodsList: [], // 商品列表
      priceDetailDTO: {}, // 商品价格
      totalNum: 0, // 购买数量
      addrId: '', // 编辑地址传入的id
      moreAddr: false, // 更多地址
      canUseCouponNum: 0, // 可用优惠券数量
      couponList: [], // 可用优惠券列表
      usedCouponId: [], // 已使用优惠券id
      selectedCoupon: {}, // 已选优惠券对象
      goodsId: '', //产品Id
      storeId: '', //店铺Id
      // qindl 2024-07-10 新增
      visitors: [],
      addRemark: '',
      payFrom: {
        addPrice: 100.0,
        subPrice: 500,
        addMark: '100',
        subMark: '500',
      },

      //------游客信息-------------
      certList: [
        { label: '身份证', value: '1' },
        { label: '护照', value: '2' },
        { label: '军官证', value: '3' },
        { label: '港澳通行证', value: '4' },
        { label: '台湾通行证', value: '5' },
        { label: '台胞证', value: '6' },
        { label: '回乡证', value: '7' },
      ],
      sexList: [
        { label: '女', value: '0' },
        { label: '男', value: '1' },
      ],
      validRules: {
        name: [{ required: true, message: '请输入', trigger: 'change' }],
        number: [{ required: true, message: '请输入', trigger: 'change' }, { validator: numberValid }],
      },

      //-----收客人-------------
      advisers: {
        list: [],
        index: -1, 
      }, 
    };
  },
  mounted() {
    this.init();
  },
  computed: {
    hsah32() {
      return hashFnv32a(this.payFrom);
    },
  },
  methods: {
    // 初始化数据
    init() {
      //商品信息
      this.getGoodsDetail();
      //配送方式
      //this.getDistribution();
    },
    getAddress() {
      // 获取收货地址列表
      memberAddress(this.searchForm).then((res) => {
        if (res.success) {
          this.addressList = res.result.records;
          this.addressList.forEach((e, index) => {
            if (e.id === this.selectedAddress.id && index > 2) {
              this.moreAddr = true;
            }
          });
        }
      });
    },
    // 2025-05-13 
    getAdviserList() {
      // 获取收货地址列表
      adviserList(this.goodsId).then((res) => {
        if (res.success) {
          this.advisers.list = res.result;
        }
      });
    },
    goAddressManage() {
      // 跳转地址管理页面
      this.$router.push('/home/MyAddress');
    },
    getAddress() {
      // 获取收货地址列表
      memberAddress(this.searchForm).then((res) => {
        if (res.success) {
          this.addressList = res.result.records;
          this.addressList.forEach((e, index) => {
            if (e.id === this.selectedAddress.id && index > 2) {
              this.moreAddr = true;
            }
          });
        }
      });
    },
    // 获取配送方式列表
    async getDistribution() {
      let shopRes = await shippingMethodList({
        way: this.$route.query.way,
      });
      let shopList;
      if (shopRes.success) {
        shopList = shopRes.result;
        let way = [];
        console.log(shopList);
        this.shippingWay.forEach((item) => {
          shopList.forEach((child) => {
            if (item.value == child) {
              way.push(item);
            }
          });
        });
        this.shippingMethod = way;
        console.log(this.shippingMethod);
      }
    },

    async getStoreAddressList() {
      getStoreAddress(this.storeId, this.searchForm).then((res) => {
        if (res.success) {
          this.storeAddressList = res.result.records;
          this.storeAddressList.forEach((e, index) => {
            if (e.id === this.selectedAddress.id && index > 2) {
              this.storeMoreAddr = true;
            }
          });
        }
      });
    },
    getGoodsDetail() {
      // 订单商品详情
      this.$Spin.show();
      cartGoodsPay({ way: this.$route.query.way }).then((res) => {
        this.$Spin.hide();
        if (res.success) {
          if (!res.result.checkedSkuList || res.result.checkedSkuList.length === 0) {
            if (res.result.skuList && res.result.skuList[0]) {
              this.$Modal.warning({
                title: '购物车存在无效商品！',
                content: '[' + res.result.skuList[0].goodsSku.goodsName + ']' + res.result.skuList[0].errorMessage,
              });
            }
            this.$router.push({
              path: '/TourOrder',
              replace: true,
            });
          }
          this.goodsList = res.result.cartList;
          this.priceDetailDTO = res.result.priceDetailDTO;
          this.skuList = res.result.skuList || [];
          this.visitors = res.result.visitorList || [];

          let skuList = this.skuList && this.skuList[0];
          if (skuList && skuList.goodsSku) {
            this.goodsType = skuList.goodsSku.goodsType;
            this.goodsId = skuList.goodsSku.goodsId;
            this.skuId = skuList.goodsSku.id;
          }

          // 游客列表 qindl 2024-07-03------------------------
          var num = skuList.num;
          var childNum = skuList.childNum;
          var length = childNum + num;
          //var orderSn   = res.result.sn;

          for (var i = this.visitors.length; i < length; i++) {
            this.visitors.push({
              id: i + 1,
              name: '',
              type: '1',
              number: '',
              sex: '0',
              age: '',
              tel: '',
            });
          }

          this.storeId = this.goodsList[0].storeId;
          if (res.result.receiptVO) {
            this.invoiceData = res.result.receiptVO;
          }

          let notSupArea = res.result.notSupportFreight;
          this.selectedCoupon = {};
          if (res.result.platformCoupon) {
            this.selectedCoupon[res.result.platformCoupon.memberCoupon.id] = res.result.platformCoupon;
          }

          if (res.result.storeCoupons && Object.keys(res.result.storeCoupons)[0]) {
            let storeMemberCouponsId = Object.keys(res.result.storeCoupons)[0];
            let storeCouponId = res.result.storeCoupons[storeMemberCouponsId].memberCoupon.id;
            this.selectedCoupon[storeCouponId] = res.result.storeCoupons[storeMemberCouponsId];
          }

          if (notSupArea) {
            let content = [];
            let title = '';
            notSupArea.forEach((e) => {
              title = e.errorMessage;
              content.push(e.goodsSku.goodsName);
            });
            this.$Modal.warning({
              title: '以下商品超出配送区域' || title,
              content: content.toString(),
            });
          }
          if (res.result.memberAddress) {
            this.selectedAddress = res.result.memberAddress;
          }
          this.getAdviserList();
          this.getAddress();
          //this.getStoreAddressList();
          this.totalNum = 0;
          for (let i = 0; i < this.skuList.length; i++) {
            this.totalNum += this.skuList[i].num;
          }
          this.usedCouponId = [];
          this.couponList = res.result.canUseCoupons;
          const couponKeys = Object.keys(this.selectedCoupon);
          if (couponKeys.length) {
            this.couponList.forEach((e) => {
              if (this.selectedCoupon[e.id] && e.id === this.selectedCoupon[e.id].memberCoupon.id) {
                this.usedCouponId.push(e.id);
              }
            });
            this.$nextTick(() => {
              this.$forceUpdate();
            });
          }
        }
      }).catch(() => {
        this.$Spin.hide();
      });
    },
    getCouponNum() {
      // 获取可用优惠券数量
      couponNum({
        way: this.$route.query.way,
      }).then((res) => {
        this.canUseCouponNum = res.result;
        if (res.result) {
          let storeArr = [];
          let skuArr = [];
          this.goodsList.forEach((e) => {
            storeArr.push(e.storeId);
            e.skuList.forEach((i) => {
              skuArr.push(i.goodsSku.id);
            });
          });
          let params = {
            pageNumber: 1,
            pageSize: 100,
            memberCouponStatus: 'NEW',
            scopeId: skuArr.toString(),
            storeId: storeArr.toString(),
            totalPrice: this.priceDetailDTO.goodsPrice,
          };
          canUseCouponList(params).then((res) => {
            // 可用优惠券列表
            if (res.success) this.couponList = res.result.records;
            const couponKeys = Object.keys(this.selectedCoupon);
            this.usedCouponId = [];
            if (couponKeys.length) {
              this.couponList.forEach((e) => {
                if (e.id === this.selectedCoupon[couponKeys].memberCoupon.id) {
                  this.usedCouponId.push(e.id);
                }
              });
              this.$nextTick(() => {
                this.$forceUpdate();
              });
            }
          });
        }
      });
    },
    selectAddress(item) {
      // 选择地址
      let params = {
        way: this.$route.query.way,
        shippingAddressId: item.id,
      };
      selectAddr(params).then((res) => {
        if (res.success) {
          this.$Message.success('选择配送方式成功');
          this.selectMethod = item;
          this.getGoodsDetail();
        }
      });
    },
    selectStoreAddress(item) {
      console.log(item.id);
      console.log(this.$route.query.way);
      // 选择自提地址
      setStoreAddressId(item.id, this.$route.query.way).then((res) => {
        if (res.success) {
          this.$Message.success('选择自提地址成功');
          this.selectedStoreAddress = item;
          this.getGoodsDetail();
        }
      });
    },
    selectDeliverMethod(item) {
      let params = {
        way: this.$route.query.way,
        shippingMethod: item.value,
      };
      setShipMethod(params).then((res) => {
        if (res.success) {
          this.selectedDeliverMethod = item.value;
          this.getGoodsDetail();
        }
      });
    },
    editAddress(id) {
      // 编辑地址
      this.addrId = id;
      this.$refs.address.show();
    },
    addrChange() {
      // 添加，编辑地址回显
      this.getAddress();
    },
    delAddress(item) {
      // 删除地址
      this.$Modal.confirm({
        title: '提示',
        content: '你确定删除这个收货地址',
        onOk: () => {
          delMemberAddress(item.id).then((res) => {
            if (res.success) {
              this.$Message.success('删除成功');
              this.getAddress();
            }
          });
        },
        onCancel: () => {},
      });
    },
    goGoodsDetail(skuId, goodsId) {
      let routeUrl = '',
        path = '/goodsDetail',
        query = {
          skuId,
          goodsId,
        };
      if ((this.goodsType = 'TOUR_GOODS')) {
        (path = '/goodsCruise'),
          (query = {
            goodsId,
          });
      }
      // 跳转商品详情
      routeUrl = this.$router.resolve({
        path: path,
        query: query,
      });
      window.open(routeUrl.href, '_blank');
    },
    // 跳转店铺首页
    goShopPage(id) {
      let routeUrl = this.$router.resolve({
        path: '/Merchant',
        query: {
          id: id,
        },
      });
      window.open(routeUrl.href, '_blank');
    },
    useCoupon(id, used) {
      // 使用优惠券
      let params = {
        way: this.$route.query.way,
        memberCouponId: id,
        used: used, // true 为使用， false为弃用
      };
      selectCoupon(params).then((res) => {
        if (res.success) this.init();
      });
    },
    editInvoice() {
      // 编辑发票信息
      this.$refs.invModal.invoiceAvailable = true;
    },

    //
    getInvMsg(item) {
      // 获取发票信息
      if (item) {
        this.init();
        this.$refs.invModal.invoiceAvailable = false;
      }
    },

    /**
     * 1、操作来源
     * 2、备注
     * 3、订单交易方式
     */
    pay() {
      // 结算
      const params = {
        client: 'PC',
        remark: [],
        way: this.$route.query.way,
      };
      this.goodsList.forEach((e) => {
        if (e.remark) {
          params.remark.push({
            remark: e.remark,
            storeId: e.storeId,
          });
        }
        if (e.addMark) {
          params.addMark = e.addMark;
        }
        if (e.subMark) {
          params.subMark = e.subMark;
        }
      });

      if (!params.remark.length) delete params.remark;
      // if (!params.addMark.length) delete params.addMark;
      // if (!params.addMark.length) delete params.addMark;
      this.$Spin.show();
      createTrade(params)
        .then((res) => {
          this.$Spin.hide();
          if (res.success) {
            if (params.way === 'POINTS' || params.way === 'TOUR') {
              // 积分支付不需要跳转支付页面
              this.$router.push('/payDone');
            } else {
              this.$router.push({
                path: '/payment',
                query: {
                  orderType: 'TRADE',
                  sn: res.result.sn,
                },
              });
            }
          }
        })
        .catch(() => {
          this.$Spin.hide();
        });
    },

    // 优惠券可用范围
    useScope(type) {
      let goods = '全部商品';
      switch (type) {
        case 'ALL':
          goods = '全部商品';
          break;
        case 'PORTION_GOODS':
          goods = '部分商品';
          break;
        case 'PORTION_GOODS_CATEGORY':
          goods = '部分分类商品';
          break;
      }
      return `${goods}可用`;
    },

    pictureUrl(path) {
      if (!path) {
        return '';
      } else if (path.indexOf('photos/') >= 0) {
        return staticUrl + '/' + path;
      } else {
        return path;
      }
    },

    // 设置购买数量
    changeNum(val, cal, id) {
      if (val) {
        setCartGoodsNum({ skuId: id, num: val, childNum: cal }).then((res) => {
          if (res.success) {
            this.getGoodsDetail();
          }
        });
      }
    },

    isNumber(value) {
      return /^-?\d+(\.\d+)?$/.test(value);
    },

    // 增项金额
    changeItemPriceBlur(add, sub, id) {
      //console.info("this.addRemark", add);
      if (!id) {
        return;
      }

      if (add && !this.isNumber(add)) {
        this.$Message.warning('填入的增项金额无效！' + add + ', ' + this.isNumber(add));
        return;
      }

      if (sub && !this.isNumber(sub)) {
        this.$Message.warning('填入的减项金额无效！' + sub);
        return;
      }

      setCartItemPrice({ skuId: id, add: add, sub: sub }).then((res) => {
        if (res.success) {
          this.getGoodsDetail();
        }
      });
    },

    // 增项金额
    changeItemMarkBlur(addMark, subMark, id) {
      //console.info("this.addRemark", addMark);
      if (!id) {
        return;
      }

      var params = {
        skuId: id,
        addMark: addMark,
        subMark: subMark,
      };

      setCartItemMark(params).then((res) => {
        if (res.success) {
          this.getGoodsDetail();
        }
      });
    },

    //--------------------------------------------------------
    formatCertType(value) {
      var text = '';
      switch (value) {
        case '1':
          text = '身份证';
          break;
        case '2':
          text = '护照';
          break;
        case '3':
          text = '军官证';
          break;
        case '4':
          text = '港澳通行证';
          break;
        case '5':
          text = '台湾通行证';
          break;
        case '6':
          text = '台胞证';
          break;
        case '7':
          text = '回乡证';
          break;
      }
      return text;
    },

    formatSex(value) {
      if (value == '0') {
        return '女';
      } else if (value == '1') {
        return '男';
      } else {
        return '';
      }
    },

    async editClosedEvent({ row, column }) {
      const $table = this.$refs.xTable;
      const field = column.field;

      if (field == 'number' && row['type'] == '1' && row[field] && (row[field].length == 15 || row[field].length == 18)) {
        row['sex'] = getSexByIdCard(row[field]) || '';
        row['age'] = getAgeByIdCard(row[field]) || '';
      }

      if (field == 'type' && row['type'] != '1') {
        row['number'] = '';
        row['sex'] = '';
        row['age'] = '';
      }

      //console.info("editClosedEvent", row, field, row[field], getSexByIdCard(row[field]));
      // 判断单元格值是否被修改
      if ($table.isUpdateByRow(row, field)) {
        setTimeout(() => {
          // VXETable.modal.message({
          //   content: `局部保存成功！ ${field}=${cellValue}`,
          //   status: 'success'
          // })
          // 局部更新单元格为已保存状态
          $table.reloadRow(row, null, field);
          this.handlerVisitor(row['id'] - 1);
        }, 300);
      }
    },

    // 保存游客信息
    handlerVisitor(index) {
      var params = Object.assign({}, this.visitors[index]);
      if (!params.name) {
        // this.$Message.error("游客姓名不能为空！");
        return false;
      }
      if (!params.number) {
        // this.$Message.error("游客证件号不能为空！");
        return false;
      }
      if (!params.tel) {
        // this.$Message.error("游客联系电话不能为空！");
        return false;
      }
      console.info('handlerVisitor@@' + params);
      visitorCache(params).then((res) => {
        if (res.success == true) {
          this.$Message.success('游客信息保存成功！');
          this.getGoodsDetail();
        }
      });
    },

    /**
     * 
     * @param index 
     * @param id 
     */
    shippingAdviser(index, id) {
      if (this.advisers.index == index) {
        this.advisers.index = -1;
        this.advisers.id = "";
      } else {
        this.advisers.index = index;
        this.advisers.id = id;
      }

      let params = {
        skuId: this.skuId,
        adviserId: id,
        way: this.$route.query.way,
      };
      setShippingAdviser(params);
    },
  },
};
</script>

<style lang="scss" scoped>
@import '../../assets/styles/coupon.scss';

.pay-order {
  background-color: #fff;
}

.goods-msg {
  overflow: hidden;
}

/** logo start */
.logo {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px auto 0;

  div:nth-child(1) {
    display: flex;
    justify-content: space-between;
    align-items: center;

    img {
      width: 150px;
      height: auto;
      cursor: pointer;
    }

    div:nth-child(2) {
      width: 200px;
      color: #999;
      font-size: 16px;
      margin: 0 20px;

      span {
        color: $theme_color;
      }
    }
  }
}

.cart-steps {
  height: 30px;
  display: flex;
  align-items: center;

  span {
    @include content_color($light_content_color);
    height: 30px;
    text-align: center;
    line-height: 30px;
    display: inline-block;
    padding: 0 15px;
  }

  .ivu-icon {
    @include content_color($light_content_color);
    font-size: 20px;
    margin: 0 15px;
  }

  .active {
    border-radius: 50px;
    background-color: $color-primary;
    color: #fff;
  }

  .active-arrow {
    color: #ff8f23;
  }
}

/** logo end */
/** content start */
.content {
  margin: 0px auto;
  background-color: #fff;
  min-height: 200px;
  padding: 0px 25px;
}

.delivery-method {
  display: flex;
  flex-wrap: wrap;

  > div {
    border: 1px dotted #949494;
    width: 50px;
    height: 40px;
    margin: 20px 20px 0 0;
    padding: 10px;
    cursor: pointer;
    color: #999;
  }

  .method-item {
    position: relative;
    font-size: 12px;

    > div:nth-child(1) {
      margin-bottom: 10px;

      span {
        margin-right: 10px;
      }

      > span:nth-child(1) {
        color: #000000;
        font-size: 14px;
      }
    }

    .edit-btn {
      font-size: 12px;
      position: absolute;
      top: 15px;
      right: 20px;
      color: $theme_color;

      span:hover {
        border-bottom: 1px solid $theme_color;
      }
    }

    .corner-icon {
      position: absolute;
      right: -1px;
      bottom: -1px;

      div {
        width: 0;
        border-top: 20px solid transparent;
        border-right: 20px solid $theme_color;
      }

      .ivu-icon {
        font-size: 12px;
        position: absolute;
        bottom: 0;
        right: 1px;
        transform: rotate(-15deg);
        color: #fff;
      }
    }
  }

  .border-red {
    border-color: $theme_color;
  }
}

/** 地址管理 */
.address-manage {
  display: flex;
  flex-wrap: wrap;

  > div {
    border: 1px dotted #949494;
    width: 265px;
    height: 120px;
    margin: 20px 20px 0 0;
    padding: 10px;
    cursor: pointer;
    color: #999;
  }

  .add-address {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;

    .ivu-icon {
      font-size: 24px;
    }
  }

  .address-item {
    position: relative;
    font-size: 12px;

    > div:nth-child(1) {
      margin-bottom: 10px;

      span {
        margin-right: 10px;
      }

      > span:nth-child(1) {
        color: #000000;
        font-size: 14px;
      }
    }

    .edit-btn {
      font-size: 12px;
      position: absolute;
      top: 15px;
      right: 20px;
      color: $theme_color;

      span:hover {
        border-bottom: 1px solid $theme_color;
      }
    }

    .corner-icon {
      position: absolute;
      right: -1px;
      bottom: -1px;

      div {
        width: 0;
        border-top: 20px solid transparent;
        border-right: 20px solid $theme_color;
      }

      .ivu-icon {
        font-size: 12px;
        position: absolute;
        bottom: 0;
        right: 1px;
        transform: rotate(-15deg);
        color: #fff;
      }
    }
  }

  .border-red {
    border-color: $theme_color;
  }
}

/** 购买商品列表 start */
.shop-name {
  display: flex;
  justify-content: space-between;

  > span:nth-child(1) {
    font-weight: bold;

    .ivu-icon {
      color: #ff8f23;

      &:hover {
        color: $theme_color;
      }
    }
  }

  > span:nth-child(2) {
    color: #999;
    position: relative;
    display: flex;
    width: 200px;
  }

  .delivery-list {
    position: absolute;
    right: 0;
    top: 20px;
    background-color: #f3fafe;
    box-shadow: 0px 0px 5px #b9b2b2;
    display: flex;
    flex-wrap: wrap;
    width: 200px;
    min-height: 100px;
    padding: 10px;

    li {
      width: 90px;
      height: 30px;
      text-align: center;

      &:hover {
        cursor: pointer;
      }
    }
  }
}

.goods-list {
  width: 1150px;
  background-color: #f8f8f8;
  margin: 10px 0 20px 0;

  .goods-item {
    width: 100%;
    padding: 20px 0;
    margin: 0 20px;
    border-bottom: 1px dotted #999;

    .goods-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 70px;
    }

    &:last-child {
      border: none;
    }

    img {
      width: 100px;
      height: 70px;
    }

    > span {
      text-align: center;
      width: 100px;
    }

    > span:nth-child(1) {
      font-size: 12px;

      flex: 1;
      text-align: left;

      > span {
        margin-left: 10px;
      }
    }

    > span:last-child {
      color: $theme_color;
      font-weight: bold;
    }

    .goods-price {
      font-size: 16px;
    }

    .Ellipsis {
      height: 22px;
      line-height: 22px;

      .item-price-title {
        display: inline-block;
        width: 50px;
        text-align: justify;
        justify-content: space-between;
        text-align-last: justify;
      }

      i {
        margin-left: 2px;
        margin-right: 5px;
      }

      .item-coupon {
        margin-right: 10px;
        color: #333;
        font-size: 14px;
      }
    }
  }
}

.goods-bottom {
  .order-mark {
    width: 600px;
    float: left;
    height: 80px;
  }

  /** 订单价格 */
  .order-price {
    text-align: right;
    width: 535px;
    float: left;
    font-size: 16px;
    color: #666;
    margin-left: 10px;
    margin-top: -8px;
    margin-bottom: 8px;

    > div > span {
      height: 25px;
      line-height: 25px;
      display: inline-block;
      margin-top: 3px;
    }

    > div > span:nth-child(2) {
      width: 130px;
      text-align: right;
      color: #333;
    }

    .actrual-price {
      color: $theme_color !important;
      font-weight: bold;
      font-size: 20px;
    }
  }
}

/** 购买商品列表 end */
/** 发票信息 start */
.invoice {
  .inv-tips {
    position: absolute;
    border: 1px solid #ddd;
    width: 310px;
    padding: 3px;
    margin: 0 0 0 10px;
    font-size: 12px !important;
    box-shadow: 0 0 3px rgba(0, 0, 0, 0.15);

    &::before {
      content: '';
      display: inline-block;
      width: 12px;
      height: 17px;
      background: url(../../assets/images/arrow-left.png) 0 0 no-repeat;
      background-color: #fff;
      position: absolute;
      left: -9px;
    }

    .ivu-icon {
      color: #ff8f23;
      margin-right: 3px;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .inovice-content {
    > table tr th {
      height: 45px;
      font-weight: 600;
    }

    > span {
      margin-right: 10px;
    }

    > span:last-child {
      color: $theme_color;
      cursor: pointer;

      &:hover {
        border-bottom: 1px solid $theme_color;
      }
    }
  }
}

/** 发票信息 end */

/** content end */
/** 底部支付栏 */
.order-footer {
  padding: 0px 25px;
  margin: 20px auto;
}

.order-footer-in {
  z-index: 20;
  height: 60px;
  @include background_color($light_white_background_color);
  @include title_color($title_color);
  display: flex;
  align-items: center;
  flex-direction: row-reverse;
  border-top: 1px solid #ddd;


  div {
    text-align: center;
  }

  position: sticky;
  bottom: 0;

  .adviser {
    border: 1px #ddd solid;
    border-radius: 8px;
    padding: 2px 10px;
    cursor: pointer;
  }

  .adviser.active {
    background-color: #fbf6f1;
    border: 1px #999 solid;
  }

  .pay {
    background-color: $theme_color;
    width: 150px;
    font-size: 20px;
    color: #fff;
    height: 100%;
    line-height: 60px;
    cursor: pointer;
    border: 1px red solid;
    margin-top: -2px;
  }
}

/** 公共表头 */
.card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #dddddd;
  height: 40px;

  span:nth-child(1) {
    font-size: 18px;
  }

  span:nth-child(2) {
    font-size: 12px;
    color: #438cde;
    cursor: pointer;

    &:hover {
      color: $theme_color;
    }
  }
}

.ivu-divider {
  background: $theme_color;
  height: 2px;
}

.pay-address {
  font-size: 12px;
}

.more-addr {
  cursor: pointer;
  margin-top: 10px;
  display: inline-block;
}

.coupon-item {
  width: 260px;
  height: 125px;
  margin-right: 10px;
  margin-bottom: 10px;

  .c-right {
    width: 30px;
    padding: 10px 7px;
  }

  b {
    background: url('../../assets/images/small-circle.png') top left repeat-y;
    right: 28px;
  }

  .circle-top,
  .circle-bottom {
    right: 22px;
  }

  .used {
    position: absolute;
    top: 60px;
    right: 40px;
    width: 50px;
    height: 50px;
  }
}

.coupon-list {
  max-height: 260px;
  overflow: scroll;
}

.supplement {
  width: 100%;
  display: block;
  margin-top: 5px;
}

.supplement .supplement_tit {
  background: #f9f9f9;
  height: 40px;
}

.supplement_text {
  border: 2px solid #f9f9f9;
  background: #fff;
  height: 40px;
}

.supplement li span {
  width: 20%;
  float: left;
  text-align: center;
}

.supplement_tit span {
  line-height: 40px;
  color: #666;
  font-size: 12px;
  font-weight: 600;
}

.supplement_text span {
  line-height: 35px;
  font-size: 12px;
}

.supplement .supplement_text .unsed {
  color: #b8b8b8;
}

.supplement_text em {
  border-radius: 50%;
  border: 1px solid #eee;
  margin: 0 10px;
  display: inline-block;
  font-size: 18px;
  text-align: center;
  height: 22px;
  width: 22px;
  line-height: 17px;
  cursor: pointer;
  color: #ea1a56;
}

.supplement .supplement_text .unsed:hover {
  border: 1px solid #eee;
}

.supplement .supplement_text .unsed {
  color: #b8b8b8;
}

.supplement_text em:hover {
  border: 1px solid #ff0048;
}
</style>
